const express = require('express');
const router = express.Router();
const { generateToken}=require('./../common/secret') 

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.post('/register',(req,res,next)=>{
  let params={...req.params,...req.search,...req.body}
  req.db.query(`select * from user where name='${params.name}'`).then((r,err)=>{
    if(!r[0].length){
      req.db.query(`insert into user (name,passwor) values ('${params.name}','${params.password}')`).then(r=>{
        res.send({
          status:200,
          data:[],
          msg:'用户注册成功'
        })
      })
    } else{
      res.send({
        status:0,
        data:[],
        msg:'用户名已注册'
      })
    }
  })
})
// 登录
router.get('/login',(req,res)=>{
  let params={...req.params,...req.search,...req.body,...req.query}
  if(params.name&&params.password){
    req.db.query(`select * from user where name='${params.name}' and passwor='${params.password}'`).then(r=>{
      if(r[0].length){
        console.log(r[0][0], 'testinfo')
        const {id,name}=r[0][0]
        const payload = { name,id }; // 自定义有效载荷，例如用户名  
        const token = generateToken(payload);  
        res.json({
          status:200,
          token:token,
          msg:'登录成功'
        })
      } else{
        res.send({
          status:0,
          data:'',
          msg:'用户名或密码错误'
        })
      }

    }).catch(e=>{
      res.send({
        status:0,
        data:'',
        msg:'登录失败'
      })
    })
  } else{
    res.send({
      status:0,
      data:'',
      msg:'用户名密码不能为空'
    })
  }
 
})

module.exports = router;
